package com.example.idie.util;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.*;
import org.springframework.boot.system.ApplicationHome;

import java.io.*;

public class FtpUtil {

    public String getSavePath() {
        // 这里需要注意的是ApplicationHome是属于SpringBoot的类
        // 获取项目下resources/static/img路径
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());

        // 保存目录位置根据项目需求可随意更改
        return applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\";
    }

    public static void sshSftp(byte[] bytes,String fileName) throws Exception{
        //指定的服务器地址
        String ip = "202.117.21.89";
        //用户名
        String user = "dell";
        //密码
        String password = "dell123.com";
        //服务器端口
        int port = 22;
        //上传文件到指定服务器的指定目录 自行修改
        String path = "/home/document/";

        Session session = null;
        Channel channel = null;

        JSch jsch = new JSch();

        session = jsch.getSession(user, ip, port);
//        if(port <=0){
//            //连接服务器，采用默认端口
//            session = jsch.getSession(user, ip);
//        }else{
//            //采用指定的端口连接服务器
//            session = jsch.getSession(user, ip ,port);
//        }

        //如果服务器连接不上，则抛出异常
        if (session == null) {
            System.out.println("session is null");
            throw new Exception("session is null");
        }

        //设置登陆主机的密码
        session.setPassword(password);//设置密码
        //设置第一次登陆的时候提示，可选值：(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间
        session.connect(30000);




        OutputStream outstream = null;
        try {
            //创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;


            //进入服务器指定的文件夹
            sftp.cd(path);

            //列出服务器指定的文件列表
//            Vector v = sftp.ls("*");
//            for(int i=0;i<v.size();i++){
//                System.out.println(v.get(i));
//            }

            //以下代码实现从本地上传一个文件到服务器，如果要实现下载，对换以下流就可以了
            outstream = sftp.put(fileName);
            outstream.write(bytes);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关流操作
            if(outstream != null){
                outstream.flush();
                outstream.close();
            }
            if(session != null){
                session.disconnect();
            }
            if(channel != null){
                channel.disconnect();
            }
        }
    }

    public void sshPrivateKeySave(byte[] bytes, String fileName) throws Exception{
        String ip = "amax6.xjtu.io";
        String user = "suyou";
        String privateKeyPath = "C:/Users/yoghurts/.ssh/id_ed25519";
        int port = 47982;
        //上传文件到指定服务器的指定目录 自行修改
        String path = "/data2/suyou/Codes/medicine/results";

        Session session = null;
        Channel channel = null;

        JSch jsch = new JSch();
        jsch.addIdentity(privateKeyPath);

        session = jsch.getSession(user, ip, port);

        //如果服务器连接不上，则抛出异常
        if (session == null) {
            System.out.println("session is null");
            throw new Exception("session is null");
        }

        //设置第一次登陆的时候提示，可选值：(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间
        session.connect(30000);




        OutputStream outstream = null;
        try {
            //创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;

            //进入服务器指定的文件夹
            sftp.cd(path);

            //以下代码实现从本地上传一个文件到服务器，如果要实现下载，对换以下流就可以了
            outstream = sftp.put(fileName);
            outstream.write(bytes);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关流操作
            if(outstream != null){
                outstream.flush();
                outstream.close();
            }
            if(session != null){
                session.disconnect();
            }
            if(channel != null){
                channel.disconnect();
            }
        }
    }

    public File sshPrivateKeyRead(String fileName) throws Exception{
        String ip = "amax6.xjtu.io";
        String user = "suyou";
        String privateKeyPath = "C:/Users/yoghurts/.ssh/id_ed25519";
        int port = 47982;
        //上传文件到指定服务器的指定目录 自行修改
        String path = "/data2/suyou/Codes/medicine/results";

        Session session = null;
        Channel channel = null;

        JSch jsch = new JSch();
        jsch.addIdentity(privateKeyPath);

        session = jsch.getSession(user, ip, port);

        String savePath = this.getSavePath();


        //如果服务器连接不上，则抛出异常
        if (session == null) {
            System.out.println("session is null");
            throw new Exception("session is null");
        }

        //设置第一次登陆的时候提示，可选值：(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间
        session.connect(30000);


        File file = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        String saveFile = savePath + fileName;
        try {
            //创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;

            //进入服务器指定的文件夹
            sftp.cd(path);

            //以下代码实现从本地上传一个文件到服务器，如果要实现下载，对换以下流就可以了
            //inputStream = sftp.get(fileName);

            file = new File(saveFile);
            if (file.exists()) {
                file.delete();
            } else {
                file.createNewFile();
            }
            fileOutputStream = new FileOutputStream(file);
            sftp.get(fileName, fileOutputStream);

            return file;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
            if(session != null){
                session.disconnect();
            }
            if(channel != null){
                channel.disconnect();
            }
        }
        return file;
    }


}
